package cert.ui;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;

import cert.model.CertAuthority;
import cert.utils.KeyGen;

public class KeyGeneratorDialog extends JDialog {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final JPanel contentPanel = new JPanel();
	private JTextField keyLengthtextField;
	private JTextField algoTextField;

	/**
	 * Create the dialog.
	 */
	public KeyGeneratorDialog() {
		setModal(true);
		setTitle("Pair Key Generator");
		setBounds(100, 100, 450, 147);
		getContentPane().setLayout(new BorderLayout());
		contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
		getContentPane().add(contentPanel, BorderLayout.CENTER);
		contentPanel.setLayout(new BorderLayout(0, 0));
		{
			JPanel panel = new JPanel();
			contentPanel.add(panel, BorderLayout.CENTER);
			panel.setLayout(new FlowLayout(FlowLayout.LEFT, 5, 5));
			{
				JLabel lblKeyLength = new JLabel("Key Length :");
				panel.add(lblKeyLength);
			}
			{
				keyLengthtextField = new JTextField();
				keyLengthtextField.setText("2048");
				panel.add(keyLengthtextField);
				keyLengthtextField.setColumns(10);
			}
			{
				JLabel lblKeyAlgorithm = new JLabel("Key algorithm :");
				panel.add(lblKeyAlgorithm);
			}
			{
				algoTextField = new JTextField();
				algoTextField.setText("RSA");
				panel.add(algoTextField);
				algoTextField.setColumns(10);
			}
			{
				JButton btnGenerate = new JButton("Generate");
				btnGenerate.addActionListener(new ActionListener() {
					public void actionPerformed(ActionEvent e) {
						try {
							int keyLength = Integer.parseInt(keyLengthtextField
									.getText());
							String algo = algoTextField.getText();
							KeyGen.generateKeyPair(keyLength, algo);

							KeyGen.SaveKeyPair(CertAuthority.keyLocation,
									KeyGen.keyPair);

							JOptionPane.showMessageDialog(
									KeyGeneratorDialog.this,
									"Key Pair generated.");

						} catch (Exception d) {
							JOptionPane.showInternalMessageDialog(
									KeyGeneratorDialog.this, d.toString());
						}
					}
				});
				panel.add(btnGenerate);
			}
		}

		this.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
		this.setVisible(true);
	}
}
